var c_i=0;
const app = getApp();
var inpage=true;
var comment_t = 0;
var current_index = 0;
var rules = {
    type: null,
    type2: null,
    type3: null,
    type4: null,
    attribute: null,
    race: null,
    level: null,
    attack_range: null,
    defend_range: null
};

Page({
    data: {
        key: null,
        article: [1,2,3,4],
        random: [1,2,3],
        trend: [1,2,3,4,5],
        desks: [1,2,3,4,5,6,7],
        result: null,
        result0: null,
        i: 0,
        rule: false,
        index: {
            type: 0,
            types: [0, 0, 0],
            attribute: 0,
            race: 0,
            level: 0,
            al: null,
            au: null,
            dl: null,
            du: null
        },
        ruleList: {
            type: ['无', '怪兽', '魔法', '陷阱'],
            types: null,
            attribute: ['无', '光', '暗', '风', '水', '炎', '地', '神', '魔', '罠'],
            race: ["无", "龙族", "战士族", "恶魔族", "魔法师族", "天使族", "不死族", "岩石族", "植物族", "昆虫族", "水族", "炎族", "雷族", "鱼族", "海龙族", "幻龙族", "恐龙族", "爬虫族", "机械族", "兽族", "鸟兽族", "兽战士族", "念动力族", "电子界族", "幻神兽族", "创造神族"],
            level: ["无", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 13]
        },
        tip: "下拉加载更多"
    },
    onLoad: function () {
        this.getArticle();
        /**this.getComments(5, (res) => {
            let trend = this.data.trend;
            res.forEach((r, i) => {
                trend[i] = r;
            })
            this.setData({
                trend: trend
            })
        });**/
        this.freshRandom();
        this.getDesks();
        const file = require('../../lib/file.js');
        let dl = new file.file();
        dl.fill();
        dl.loadFont();
    },
    onShow: function () {
        this.clear_rules();
        inpage=true;
    },
    onHide() {
        inpage=false;
    },
    toPage: function (res) {
        const rl = require('../../lib/search.js');
        const rule = new rl.Rule(key, rules);
        var password = res.currentTarget.dataset._id;
        wx.navigateTo({
            url: '../../pages/cardIfm/cardIfm?password=' + password + rule.zip,
        })
    },
    toArticle: function (res) {
        var _id = res.currentTarget.dataset._id;
        wx.navigateTo({
            url: '../../pages/article/article?_id=' + _id,
        })
    },
    ansysTarget: function (res) {
        var _id = res.currentTarget.dataset._id;
        var type = res.currentTarget.dataset.type;
        if (type == "article") {
            wx.navigateTo({
                url: '../../pages/article/article?_id=' + _id,
            })
        }
        else {
            wx.navigateTo({
                url: '../../pages/cardIfm/cardIfm?password=' + _id,
            })
        }
    },
    keyChange: function (e) {
        this.setData({ key: e.detail.value });
    },
    search: function (e) {
        const that = this;
        var key = this.data.key;
        var rule = rules;
        const rl = require('../../lib/search.js');
        const rule_ = new rl.Rule({
            keywords: key,
            rule
        });
        wx.navigateTo({
            url: '../../pages/result/result?' + rule_.zip,
        })
    },
    getArticle: function () {
        wx.setNavigationBarTitle({
            title: '正在刷新 ',
        })
        wx.showNavigationBarLoading();
        var that = this;
        const db = wx.cloud.database();
        db.collection("article").where({
            title: db.RegExp({
                regexp: ".*",
                options: "s"
            })
        })
            .get({
                success(res) {
                    var article = res.data.reverse();
                    that.setData({
                        article: article
                    });
                    that.randomCard();
                    wx.setNavigationBarTitle({
                        title: ' ',
                    })
                    wx.hideNavigationBarLoading();
                    wx.stopPullDownRefresh();
                }
            })

    },
    changeData: function (list) {
        var prop1 = ['light', 'dark', 'wind', 'water', 'fire', 'ground', 'god'];
        var prop2 = ['光', '暗', '风', '水', '炎', '地', '神'];
        for (var i = 0; i < list.length; i++) {
            var new_prop = prop2[prop1.indexOf(list[i].attribute)];
            list[i].attribute = new_prop;
            var txt = this.race_text(list[i].type, list[i].type2, list[i].type3, list[i].type4, list[i].race);
            list[i].race_text = txt;
        }
        return list;
    },
    onPullDownRefresh: function () {
        if (!this.data.rule) {
            this.getArticle();
        }
    },
    changeType: function (res) {
        var ruleList = this.data.ruleList;
        var index = this.data.index;
        index.type = res.detail.value;
        if (res.detail.value == 0) {
            rules.type = null;
            rules.type2 = null;
            rules.type3 = null;
            rules.type4 = null;
            rules.attribute = null;
            rules.race = null;
            rules.level = null;
            rules.attack_range = null;
            rules.defend_range = null;
        }
        else if (res.detail.value == 1) {
            rules.type = 'monster';
            rules.type2 = null;
            rules.type3 = null;
            rules.type4 = null;
            rules.attribute = null;
            rules.race = null;
            rules.level = null;
            rules.attack_range = null;
            rules.defend_range = null;
            ruleList.types = [
                ['无', '通常', '效果', '仪式', '融合', '同调', '超量', '连接'],
                ['无', '通常', '调整', '灵魂', '二重', '同盟', '反转', '卡通', '特殊召唤', '灵摆'],
                ['无', '通常', '调整', '灵魂', '二重', '同盟', '反转', '卡通', '特殊召唤'],
            ]
        }
        else if (res.detail.value == 2) {
            rules.type = 'magic';
            rules.type3 = null;
            rules.type4 = null;
            rules.attribute = null;
            rules.race = null;
            rules.level = null;
            rules.attack_range = null;
            rules.defend_range = null;
            ruleList.types = [
                ['无', '通常', '永续', '速攻', '装备', '场地', '仪式']
            ]
        }
        else {
            rules.type = 'tragic';
            rules.type3 = null;
            rules.type4 = null;
            rules.attribute = null;
            rules.race = null;
            rules.level = null;
            rules.attack_range = null;
            rules.defend_range = null;
            ruleList.types = [
                ['无', '通常', '永续', '反击']
            ]
        }
        this.setData({
            ruleList: ruleList,
            index: index
        })
    },
    showRules: function () {
        if (!this.data.rule) {
            var rule = true;
        }
        else {
            var rule = false;
        }
        this.setData({
            rule: rule
        })
    },
    changeType2: function (res) {
        var types = res.detail.value;
        if (this.data.index.type == 1) {
            var typeList = [null, 'tc', 'xg', 'ys', 'rh', 'tt', 'cl', 'lj'];
            var typeList2 = [null, 'tc', 'tz', 'lh', 'ec', 'tm', 'fz', 'kt', 'sm', 'lb'];
            var type2 = typeList[types[0]];
            var type3 = typeList2[types[1]];
            var type4 = typeList2[types[2]];
            var index = [types[0], types[1], types[2]]
        }
        else if (this.data.index.type == 2) {
            var typeList = [null, 'tc', 'yx', 'sg', 'zb', 'cd', 'ys'];
            var type2 = typeList[types[0]];
            var type3 = null, type4 = null;
            var index = [types[0], 0, 0]
        }
        else if (this.data.index.type == 3) {
            var typeList = [null, 'tc', 'yx', 'fj'];
            var type2 = typeList[types[0]];
            var type3 = null, type4 = null;
            var index = [types[0], 0, 0]
        }

        var index0 = this.data.index;
        rules.type2 = type2;
        rules.type3 = type3;
        rules.type4 = type4;
        index0.types = index;
        this.setData({
            index: index0
        })
    },
    changeAttribute: function (res) {
        var attributeList = [null, 'light', 'dark', 'wind', 'water', 'fire', 'ground', 'god'];
        var attribute = attributeList[res.detail.value];
        var index = this.data.index;
        rules.attribute = attribute;
        index.attribute = res.detail.value;
        this.setData({
            index: index
        })
    },
    changeRace: function (res) {
        var raceList = [null, "龙族", "战士族", "恶魔族", "魔法师族", "天使族", "不死族", "岩石族", "植物族", "昆虫族", "水族", "炎族", "雷族", "鱼族", "海龙族", "幻龙族", "恐龙族", "爬虫族", "机械族", "兽族", "鸟兽族", "兽战士族", "念动力族", "电子界族", "幻神兽族", "创造神族"];
        var race = raceList[res.detail.value];
        var index = this.data.index;
        rules.race = race;
        index.race = res.detail.value;
        this.setData({
            index: index
        })
    },
    changeLevel: function (res) {
        var levelList = [null, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 13];
        var level = levelList[res.detail.value];
        var index = this.data.index;
        rules.level = level;
        index.level = res.detail.value;
        this.setData({
            index: index
        })
    },
    changeAL: function (res) {
        var al = res.detail.value;
        var index = this.data.index;
        index.al = al;
        if (!rules.attack_range) {
            if (al == "") {
                var ar = null;
            }
            else {
                var ar = [al, 5000];
            }
        }
        else {
            var up = rules.attack_range[1];
            if (al == "") {
                var ar = [0, 5000]
            }
            else {
                var ar = [al, up];
            }
        }
        rules.attack_range = ar;
        this.setData({
            index: index
        })
    },
    changeAU: function (res) {
        var au = res.detail.value;
        var index = this.data.index;
        index.au = au;
        if (!rules.attack_range) {
            if (au == "") {
                var ar = null;
            }
            else {
                var ar = [0, au];
            }
        }
        else {
            var low = rules.attack_range[0];
            if (au == "") {
                var ar = [0, 5000]
            }
            else {
                var ar = [low, au];
            }
        }
        rules.attack_range = ar;
        this.setData({
            index: index
        })
    },
    changeDL: function (res) {
        var dl = res.detail.value;
        var index = this.data.index;
        index.dl = dl;
        if (!rules.defend_range) {
            if (dl == "") {
                var dr = null;
            }
            else {
                var dr = [dl, 5000];
            }
        }
        else {
            var up = rules.defend_range[1];
            if (dl == "") {
                var dr = [0, 5000]
            }
            else {
                var dr = [dl, up];
            }
        }
        rules.defend_range = dr;
        this.setData({
            index: index
        })
    },
    changeDU: function (res) {
        var du = res.detail.value;
        var index = this.data.index;
        index.du = du;
        if (!rules.defend_range) {
            if (du == "") {
                var dr = null;
            }
            else {
                var dr = [0, du];
            }
        }
        else {
            var low = rules.defend_range[0];
            if (du == "") {
                var dr = [0, 5000]
            }
            else {
                var dr = [low, du];
            }
        }
        rules.defend_range = dr;
        this.setData({
            index: index
        })
    },
    clear_rules: function () {
        this.setData({
            rules: {
                type: null,
                type2: null,
                type3: null,
                type4: null,
                attribute: null,
                race: null,
                level: null,
                attack_range: null,
                defend_range: null
            },
            rule: false,
            index: {
                type: 0,
                types: [0, 0, 0],
                attribute: 0,
                race: 0,
                level: 0,
                al: null,
                au: null,
                dl: null,
                du: null
            }
        })
    },
    randomCard: function (num = 1, callback = function (res_) {
        this.setData({
            random: res_
        })
    }) {
        var that = this;
        const db = wx.cloud.database();
        var r = Math.floor(Math.random() * 9552);
        db.collection("card").limit(num).skip(r).get({
            success: function (res) {
                let randoms = [];
                res.data.forEach((card, i, result) => {
                    var password = card._id;
                    var name = card.name;
                    var desc = card.desc.split("\n").join("");
                    var random = {
                        _id: password,
                        title: name,
                        view: desc,
                        pic: "cloud://cards-2c53b0.6361-cards-2c53b0/pic/" + password + ".jpg"
                    };
                    randoms.push(random)
                })
                callback.call(that, randoms);
            }
        })
    },
    freshRandom() {
        const that = this;
        this.setData({
            random: 1
        })
        this.randomCard(1, function (res) {
            setTimeout(function () {
                that.setData({
                    random: res[0]
                })
            }, 1000)
        })
    },
    getComments(num = 2, callback = function () { }) {
        const db = wx.cloud.database();
        db.collection("comments").limit(num).skip(comment_t).where({
            orign: 'card'
        }).orderBy('time', 'desc').get({
            success: function (res) {
                if (res.data.length >= 0) {
                    res.data.forEach((r, i) => {
                        if (r.comment) {
                            r.comment = r.comment.length > 15 ? r.comment.slice(0, 15) + "..." : r.comment;
                        }
                        let date = new Date(r.time);
                        r.date = (date.getMonth() + 1) + "月" + date.getDate() + "日 " + date.getHours() + ":" + date.getMinutes();
                    })
                    comment_t += num;
                    callback(res.data);
                }
                else {
                    comment_t = 0;
                }
            },
            fail() {
                comment_t = 0;
            }
        })
    },
    freshComment() {
        c_i++;
        if (c_i%20 == 0 && inpage) {
            let trend = this.data.trend;
            this.getComments(5, (res) => {
                let trend=this.data.trend;
                res.forEach((r,i)=>{
                    trend[i]=r;
                })
                this.setData({
                    trend: trend
                })
            })
            c_i=0;
        }
    },
    toComment(e) {
        let key = e.currentTarget.dataset.key;
        wx.navigateTo({
            url: '../comment/comment?id='+key+'&orign=card',
        })
    },
    getDesks() {
        const Desk=require('../../lib/cardDesk.js');
        Desk.getCloudDesk((res)=> {
            this.setData({
                desks: res
            })
        })
    }
})
